import React, {useState, useEffect, useRef} from 'react'
import { 
  PageHeader, 
  Steps, 
  Button,
  Input,
  Form,
  notification,
  Select } from 'antd';
import style from './news-manage.module.css'
import axios from 'axios'
import NewsEditor from '../../../components/news-manage/NewsEditor';
import {store} from '../../../store';

const { Option } = Select;
const { Step } = Steps;

const layout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 20 },
};

export default function Add(props) {
  const [stepFlag, setStepFlag] = useState(0)
  const [categoryData, setCategoryData] = useState([])
  const [formInfo, setFormInfo] = useState({})
  const [constent, setConstent] = useState('')
  const user = JSON.parse(localStorage.getItem('token'))
  const NewsForm = useRef(null)
  useEffect(() => {
    console.log(props.match.params.id)
    axios.get('https://mock.mengxuegu.com/mock/6190fd8cf126df7bfd5b75e8/userList/queryNewsDetail').then(res => {
      const {data: {data}} = res
      const {note, gender, content} = data
      // setnewsInfo(data)
      NewsForm.current.setFieldsValue({
        note,
        gender
      })
      setConstent(content)
    })
  }, [props.match.params.id])
  useEffect(() => {
    axios.get('/userList/getNewsCategory').then(response => {
      const {data: {data}} = response
      setCategoryData(data)
    })
  }, [])

  const handleNext = () => {
    if (stepFlag === 0) {
      NewsForm.current.validateFields().then(response => {
        setStepFlag(stepFlag + 1)
        console.log(response, 999999)
        setFormInfo(response)
      })
    } else {
      if (constent === '' || constent.trim() === "<p></p>") {
        return 
      }
      console.log(formInfo, constent)
      setStepFlag(stepFlag + 1)
    }
  }
  const handlePrevious = () => {
    setStepFlag(stepFlag - 1)
  }
  const onGenderChange = () => {}
  const onFinish = () => {}
  const send = () => {
    let formData = JSON.parse(JSON.stringify(formInfo))
    let obj= {
      ...formData,
      content: constent,
      region: user.region ? user.region : '全球',
      author: user.userName,
      roleId: user.roleId,
      audioState: 1,
      publishState: 0,
      createTime: Date.now(),
      start: 99,
      view: 7,
      publishTime: 0
    }
    let action = {
      type: 'sendNews',
      value: {
        ...obj
      }
    }
    console.log({...formInfo}, 'formInfo')
    store.dispatch(action)
    console.log(store.getState(),  '添加')
    const args = {
      message: '通知',
      description:
        '添加成功',
      duration: 0,
    };
    notification.open(args);
    props.history.push('/news-manage/draft')
  }
  return (
    <div>
      <PageHeader
        className="site-page-header"
        onBack={() => props.history.goBack()}
        subTitle="R4O计划全球指挥中心新闻总署"
        title="更新新闻"
      />
      <Steps current={stepFlag}>
        <Step title="基本信息" description="新闻标题,新闻分类" />
        <Step title="新闻内容" description="新闻主体内容." />
        <Step title="新闻提交" description="保存草稿或提交审核" />
      </Steps>
      <div style={{marginTop: '30px'}}>
        <div className={stepFlag === 0 ? '' : style.hidden}>
        <Form 
          ref={NewsForm}
          {...layout} 
          name="control-hooks" 
          onFinish={onFinish}
        >
        <Form.Item name="note" label="新闻标题" rules={[{ required: true }]}>
          <Input />
        </Form.Item>
        <Form.Item name="gender" label="新闻分类" rules={[{ required: true }]}>
          <Select
            placeholder="Select a option and change input text above"
            onChange={onGenderChange}
            allowClear
          >
            {
              categoryData.map((item) => {
                return <Option value={item.value} key={item.id}>{item.title}</Option>
              })
            }
          </Select>
        </Form.Item>
        <Form.Item
          noStyle
          shouldUpdate={(prevValues, currentValues) => prevValues.gender !== currentValues.gender}
        >
          {({ getFieldValue }) =>
            getFieldValue('gender') === 'other' ? (
              <Form.Item name="customizeGender" label="Customize Gender" rules={[{ required: true }]}>
                <Input />
              </Form.Item>
            ) : null
          }
        </Form.Item>
      </Form>
        </div>
        <div className={stepFlag === 1 ? '' : style.hidden}>
          <NewsEditor content={constent} getContent={(val) => {setConstent(val)}}></NewsEditor>
        </div>
        <div className={stepFlag === 2 ? '' : style.hidden}>3</div>


      </div>

      <div style={{marginTop: '50px'}}>
        {
          stepFlag > 0 && <Button onClick={handlePrevious}>上一步</Button>
        }
        {
          stepFlag < 2 && <Button onClick={handleNext}>下一步</Button>
        }      
        {
          stepFlag === 2 && <>
            <Button>保存草稿</Button>
            <Button onClick={send}>提交审核</Button>
          </>
        }
      </div>
    </div>
  )
}
